package com.zhixin.zhixinwaimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixin.zhixinwaimai.dto.DishDto;
import com.zhixin.zhixinwaimai.entity.Dish;
import com.zhixin.zhixinwaimai.entity.DishFlavor;
import com.zhixin.zhixinwaimai.mapper.DishMapper;
import com.zhixin.zhixinwaimai.service.DishFlavorService;
import com.zhixin.zhixinwaimai.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本信息到菜品表dish
        this.save(dishDto);

        Long id = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //请求体中的flavor是一个list，将这个list里面封装了口味对象，将里边的对象抽取出来也就是item，设置该口味的dishid，然后在给它包起来成list
        flavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //然后将菜品口味数据添加到口味表
        dishFlavorService.saveBatch(flavors);
    }
    //根据id查询菜品和对应的口味
    @Override
    public DishDto getByidWithFlavor(Long id) {
        //条件构造器
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //保存菜品基本信息到菜品表dish
        this.updateById(dishDto);
        //清理原来口味表中对应的数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        Long id = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //请求体中的flavor是一个list，将这个list里面封装了口味对象，将里边的对象抽取出来也就是item，设置该口味的dishid，然后在给它包起来成list
        flavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //然后将菜品口味数据添加到口味表
        dishFlavorService.saveBatch(flavors);
    }
}
